#include "ace/Log_Msg.h"
#include "ace/Reactor.h"
#include "ace/Service_Config.h"
#include "ace/Thread_Manager.h"

#include <arpa/inet.h>

#include "Reply_Handler.h"
#include "Announce_Handler.h"

using namespace std;

ACE_THR_FUNC_RETURN event_loop (void *);

int ACE_TMAIN (int argc, ACE_TCHAR *argv [])
{
	//ACE_LOG_MSG->priority_mask (LM_INFO | LM_DEBUG, ACE_Log_Msg::PROCESS);

	char *hostname = "some-random-host.local";

	struct mdnsd *svr = mdnsd_start ();

	mdnsd_set_hostname (svr, hostname, inet_addr ("192.168.1.3"));

	const char *txt[] = {
		"srcvers=101.10",
		"feature=0x39f7",
		"deviceid=E0:CB:4E:AE:E0:31",
		NULL
	};

	struct mdns_service *svc = mdnsd_register_svc (svr, "Kyoungho",
	"_airplay._tcp.local", 39999, NULL, txt);

	mdns_service_destroy (svc);

	ACE_Reactor *reactor = ACE_Reactor::instance ();

	MDNS::Announce_Handler *announce_handler = new MDNS::Announce_Handler
		(reactor);
	announce_handler->open (svr);

	MDNS::Reply_Handler *reply_handler = new MDNS::Reply_Handler (reactor);
	reply_handler->open (svr);

	ACE_Thread_Manager::instance ()->spawn (event_loop, reactor);
	reactor->run_reactor_event_loop ();
	return ACE_Thread_Manager::instance ()->wait ();
}

ACE_THR_FUNC_RETURN event_loop (void *arg) {
	ACE_Reactor *reactor = static_cast<ACE_Reactor *> (arg);

	reactor->owner (ACE_OS::thr_self());
	reactor->run_reactor_event_loop ();
	return 0;
}
